package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Permission;
import com.itheima.service.PermissionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/sys_permission")
public class PermissionController {

    @Reference
    private PermissionService permissionService;
    /**
     * 查询所有权限信息
     * @return
     */
    @GetMapping("/findAllPermission")
    public Result findAllPermission(){
        try {
            List<Permission> list = permissionService.findAllRole();
            return new Result(true, MessageConstant.QUERY_Role_SUCCESS,list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_Role_FAIL);
        }
    }

    /**
     * 分页查询权限数据
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(QueryPageBean queryPageBean){
        try {
            PageResult pageResult = permissionService.findPage(queryPageBean);
            return new Result(true,MessageConstant.QUERY_PERMISSION_SUCCESS,pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_PERMISSION_FAIL);
        }
    }


    /**
     * 新增权限信息
     * @param permission
     * @return
     */
    @PostMapping("/savePermission")
    public Result savePermission(@RequestBody Permission permission){
        try {
            permissionService.savePermission(permission);
            return new Result(true,MessageConstant.ADD_PERMISSION_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_PERMISSION_FAIL);
        }
    }

    /**
     * 根据id删除权限信息
     * @param id
     * @return
     */
    @DeleteMapping("/deletePermission/{id}")
    public Result deletePermission(@PathVariable Integer id){
        try{
            permissionService.deletePermission(id);

            return new Result(true,MessageConstant.DELETE_PERMISSION_SUCCESS);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_PERMISSION_FAIL);
        }
    }

    /**
     * 更新权限信息
     * @param permission
     * @return
     */
     @PutMapping("/updatePermission")
     public Result updatePermission(@RequestBody Permission permission){
         try {
             permissionService.updatePermission(permission);
             return new Result(true,MessageConstant.EDIT_PERMISSION_SUCCESS);
         } catch (Exception e) {
             e.printStackTrace();
             return new Result(false,MessageConstant.EDIT_PERMISSION_FAIL);
         }
     }
}
